import * as React from 'react';
import { View, Text,Image, StatusBar, StyleSheet, TouchableOpacity, TouchableWithoutFeedback, Keyboard } from 'react-native';
import { pxToDp } from '../../utils/stylesKits';
import { Input } from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';
import validator from '../../utils/validator';
import request from '../../utils/request';
import Toast from 'react-native-toast-message';
import  { Loading } from '../../components/custmerToast'; 
import { MyContext } from '../../store';
import { inject, observer } from 'mobx-react';
import LinearGradient from 'react-native-linear-gradient';
import { CodeField, Cursor, useBlurOnFulfill } from 'react-native-confirmation-code-field';
import { set } from 'mobx';
export default function Login(props) {
  const onChangeNumber = (number) => { };
  const [phone, setPhone] = React.useState('');
  const [errorMessage, setErrorMessage] = React.useState('');
  const [isLoading, setIsLoading] = React.useState(false);
  const [vcodeTxt, setVcodeTxt] = React.useState('');
  const [btnText, setBtnText] = React.useState('重新获取');
  const [showCode, setShowCode] = React.useState(false);
  const [isCountDowning, setIsCountDowning] = React.useState(false);
  const onPressPhone = async()=> {
    if(errorMessage) {
      return;
    }
    const res = await request.get('login.json', {phone});
    if(res.name) {
      setShowCode(true);
      countDown();
    }
    
  }
  const countDown = () => {
    if(isCountDowning) {
      return;
    }
    setIsCountDowning(true);
    let seconds = 5;
    setBtnText(`重新获取(${seconds}s)`);
    let timeId = setInterval(() => {
      
      seconds--;
      console.error(seconds, 111)
      setBtnText(`重新获取(${seconds}s)`);
      if (seconds == 0) {
        clearInterval(timeId);
        setIsCountDowning(false);
        setBtnText(`重新获取`);
      }
    }, 1000);
  }
  const changePhone = (phoneNew) => {
    setPhone(() => phoneNew);
  }
  const changeText = (text) => {
    setVcodeTxt(() => text);
  }
  const onSubmitEditing = () => {
    console.error(phone, '电话号码')
    if (validator.validatePhone(phone)) {
      setErrorMessage('');
    } else {
      setErrorMessage('手机号码错误');
      Toast.show({
        type: 'error',
        text1: '手机号码错误',
        props: { uuid: 'bba1a7d0-6ab2-4a0a-a76e-ebbe05ae6d70' }
      });
    }  
  }
  
  const context =  React.useContext(MyContext);
  React.useEffect(() => {
    // request.get('login.json', {}).then(console.log)
    // setTimeout(() => {
     
    //   // context.userInfo.setUserInfo({name: '梅斯德斯奔驰'})
    //   // console.error(context.userInfo.getUserInfo(), 'context')
    //   console.error(context.userInfo.userInfo.name, '梅西ID啊我的娃')
    // }, 3000);
  }, []);
  const codeRef = useBlurOnFulfill({vcodeTxt, cellCount: 6});
  const phoneRef = React.useRef(null);
  const onVcodeSubmitEditing = () => { 
    if (vcodeTxt.length < 6) {
      Toast.show({
        type: 'error',
        text1: '验证码错误',
        props: { uuid: 'bba1a7d0-6ab2-4a0a-a76e-ebbe05ae6d70' }
      });
    } else {
      Keyboard.dismiss();
    }
  }
  const RenderCode = React.useMemo(()=>  { 
    return (<View style={styles.inputCode}>
      <Text style={[styles.inpiutTxt, styles.noPadding]}>获取验证码</Text>
      <View style={{ marginTop: pxToDp(5) }}><Text style={{ color: "#888" }}>已发到:+86 {phone}</Text></View>
      <View style={{ marginBottom: pxToDp(20) }}>
        <CodeField
          value={vcodeTxt}
          onChangeText={changeText}
          onSubmitEditing={onVcodeSubmitEditing}
          cellCount={6}
          rootStyle={styles.codeFiledRoot}
          keyboardType="number-pad"
          renderCell={({ index, symbol, isFocused }) => (
            <Text key={index} style={[styles.cell, isFocused && styles.focusCell]} >{symbol || (isFocused ? <Cursor /> : null)}</Text>
          )}
        />
      </View>
      <TouchableOpacity  onPress={onPressPhone}>
        <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} colors={['#9b63cd', '#e0708c']} style={styles.linearGradient}>
          <Text style={styles.buttonText}>{btnText}</Text>
        </LinearGradient>
      </TouchableOpacity>
    </View>)
  }, [vcodeTxt, btnText]);
  const RenderLogin = React.useMemo(()=>  {
    return  (
      <View>
      <View style={{ paddingBottom: pxToDp(2) }}>
        <Text style={styles.inpiutTxt}>手机号登录注册</Text>
      </View>
      <View style={styles.inpiutTel}>
        <Input placeholder="请输入手机号" 
          ref={phoneRef}
          value={phone}
          style={styles.inpiutTel}
          maxLength={11}
          keyboardType='phone-pad'
          inputStyle={{color: '#333'}}
          onChangeText={changePhone}
          errorMessage={errorMessage}
          onSubmitEditing={onSubmitEditing}
          leftIcon={{type: 'font-awesome', name: 'phone', color: '#ccc'}}>
        </Input>
        <TouchableOpacity style={styles.arginCode} onPress={onPressPhone}>
          <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} colors={['#9b63cd', '#e0708c']} style={styles.linearGradient}>
            <Text style={styles.buttonText}>登录</Text>
          </LinearGradient>
        </TouchableOpacity>
      </View>
      </View>
    )
  }, [phone, btnText]);
  React.useEffect(() => {
    // console.error(props, 'props父组件')
    // props.navigation.navigate('Details')
  }, []);

  return (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
      <View>
        {/* <View style={{height: pxToDp(50)}}> 
            <Text style={{ fontSize: 20, color: '#333'}}>梅西{context.userInfo.userInfo.name}</Text>
        </View> */}
        {/* 背景图片  translucent={true} 往上移动*/}
        <StatusBar backgroundColor="transparent" translucent={true}></StatusBar>
        <Image style={styles.pic} source={require('../../res/profileBackground.jpg')} />
        { showCode ? RenderCode : RenderLogin }
      </View>
    </TouchableWithoutFeedback>
  );
}
const styles = StyleSheet.create({
  pic: {
    width: '100%',
    height: pxToDp(200)
  },
  inpiutTxt: {
    width: '100%',  
    marginLeft: 'auto',
    marginRight: 'auto',
    marginTop: pxToDp(10),
    paddingLeft: pxToDp(20),
    fontSize: 20,
    color: '#333'
  },
  inpiutTel : {
    width: '90%',
    marginLeft: 'auto',
    marginRight: 'auto',
    borderBottomColor: '#ccc',
    placeholderTextSize: 120
  },
  linearGradient: {
    paddingLeft: 15,
    paddingRight: 15,
    borderRadius: 5,
    height: pxToDp(50),
    justifyContent: "center",
    alignItems: "center",
    color: 'white',
    borderRadius: pxToDp(45)
  },
  buttonText: {
    fontSize:  pxToDp(14),
    fontFamily: 'Gill Sans',
    textAlign: 'center',
    margin: 10,
    color: '#ffffff',
    backgroundColor: 'transparent',
  },
  bottomViewTou: {
    marginTop: pxToDp(10),
		width: '100%',
    textAlign: 'left',
    paddingLeft: pxToDp(20),
  },
  textStyle: { 
		fontSize: 14, 
		color: 'red', 
  },
  codeFiledRoot: { marginTop: 20 },
  cell: {
    width: 40,
    height: 40,
    lineHeight: 38,
    fontSize: 24,
    borderBottomWidth: 2,
    borderColor: '#00000030',
    textAlign: 'center',
    color: "#7d53ea"
  },
  focusCell: {
    borderColor: '#7d53ea'
  },
  noPadding: {
    paddingLeft: 0
  },
  inputCode: {
    width: '90%',  
    marginLeft: 'auto',
    marginRight: 'auto',
    marginTop: pxToDp(10),
    fontSize: 20,
    color: '#333'
  },
})